package com.nicholas.exampleweb.controller;

import com.alibaba.fastjson.JSON;
import com.nicholas.exampleweb.model.User;
import com.nicholas.exampleweb.service.UserService;
import com.nicholas.week1.annotation.Controller;
import com.nicholas.week1.annotation.Inject;
import com.nicholas.week1.annotation.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.HttpMethod;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@Controller
@URL("/user")
public class UserController {

    @Inject
    private UserService userService;

    @URL(value = "/register",method = HttpMethod.POST)
    public void register(HttpServletRequest request, HttpServletResponse response) {
        User user = readEntity(request,User.class);
        userService.register(user);
    }

    private <T> T readEntity(HttpServletRequest request, Class<T> clazz) {
        try {
            BufferedReader reader = request.getReader();
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            return JSON.parseObject(sb.toString(),clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @URL(value = "/queryAll",method = HttpMethod.GET)
    public String queryAll(HttpServletRequest request, HttpServletResponse response) {
        List<User> users = userService.queryAll();
        for (User user : users) {
            System.out.println(JSON.toJSONString(user));
        }
        return "/index.jsp";
    }

}
